import '@js/init.js'
import{addData,subjectData,classRender} from '../utils/getData'
//渲染动态框
objectlistRender() 
async function  objectlistRender() {
    const data = await subjectData();
    const texthtml = data.map(item => {
        return ` <option value="${item._id}">${item.name}</option>`
    });
    $('#studentSubject').html(texthtml);
    let id = $('#studentSubject').val();
    const rem= await  classRender(id);
    $('#studentClass').empty();
    rem.forEach(elem => {
   $('#studentClass').append(`<option value="${elem._id}">${elem.name}</option>`);
    });
}
$('#studentSubject').change( async  function () {
    let id = $('#studentSubject').val();
    const rem= await  classRender(id);
    $('#studentClass').empty();
    rem.forEach(elem => {
   $('#studentClass').append(`<option value="${elem._id}">${elem.name}</option>`);
    });
  })
  

//点击添加
$('#addStudentsBtn').click(function () {

  
        let name = $('#addStudentsName').val();
        let age = $('#addStudentsAge').val();
        let sex = $("[name=addStudentsGender]:checked").val();
        let object = $('#studentSubject').val();
        let clas = $('#studentClass').val();
        let urlImage = $('#showImage').attr('src')
        // console.log(object, clas);
        const rem= addData('/students/creatStudent','post',{ name: name,
            age: age,
            sex: sex,
            objectId: object,
            clasId: clas ,
            urlImage:urlImage
        });
            if(rem){
                alert('添加成功')
            }
       
  });

  //图片添加
  $('#uploadImages').change(function() {
    const files = this.files;
   // 1. 创建表单对象
   const fd = new FormData();
   // 2. 将图片信息添加到表单对象中
   fd.append('file', files[0]);

   $.ajax({
    url: '/images/uploadImages',
    type: 'POST',
    data: fd,
    // 设置 jquery 不要对图片数据进行额外的处理
    contentType: false, 
    processData: false,
    cache: false,
    headers: {
        Authorization: localStorage.token
    },
    success(res) {
        $('#showImage').attr('src',`http://localhost:3000${res.result}`)
        // console.log('图片上传结果', res);
    },
    error(err){
        if(err.status == 401){
            alert('你还未登录，请先登录');
            location.href = '../login.html';
        }
    }
})
})